#'###########################################
#'                                          #
#'  ------------------------------------    #
#'  |     COIN     __                  |    #
#'  |            >(' )                 |    #
#'  |              )/                  |    #
#'  |             /  `----/            |    #
#'  |             \  ~=- /             |    #
#'  |   ~^~^~^~^~^~^~^~^~^~^~^~^~^~^   |    #
#'  ------------------------------------    #
#'                                          #
#'###########################################



MobileData <- setClass("MobileData", representation(deployment = "character", date = "character", gpsId="character", 
        gps="data.frame", argos="data.frame"))

extractMobileData <- function(courses, write=FALSE, gpscolumns=c("Time", "Position"),
                      argoscolumns=c("Platform.ID.", "Latitude", "Longitude", "Loc..quality", "Loc..date",
                          "Sat.", "Error.radius", "Semi.major.axis", "Semi.minor.axis", "Ellipse.orientation"),
											destdir=".") {
										
  result <- list()
  cpt <- 1
  for (course in courses) {
    data <- new("MobileData")
    infos <- unlist(strsplit(course, "/"))
    data@date <- infos[length(infos) - 1]
    data@gpsId <- infos[length(infos)]
    
    files <- getDataFiles(course)
		
    gpsdata <- getData(files$gps , gpscolumns)
		#'# GPS : Extract latitude and longitude from gps data
		gpsdata <- extractGPSCoordinates(gpsdata)
		gpsdata[, time := as.POSIXct(time, format="%d/%m/%Y %H:%M:%S", tz="EST5EDT")]
		gpsdata[, deployment := cpt]
    setcolorder(gpsdata, c(ncol(gpsdata), 1:(ncol(gpsdata)-1)))
		
    argosdata <- getData(files$argos, argoscolumns, is.argos=TRUE)
    #'# Argos : project coordinates in NAD83, UTM 17
    argosdata <- projectArgosCoordinates(argosdata)
		argosdata[, time := as.POSIXct(date, tz="GMT")]
		argosdata[, time := as.POSIXct(format(time, tz="EST5EDT", usetz=TRUE))]
    argosdata[, deployment := cpt]
    setcolorder(argosdata, c(ncol(argosdata), 1:(ncol(argosdata)-1)))
		
    data@gps <- gpsdata
    data@argos <- argosdata
    data@deployment <- formatC(cpt, width = 2, flag = '0') 
    
    if (write) {
      write.table(argosdata, paste(destdir, "/", "Argos_", data@date, "_", data@gpsId, ".txt", sep=""), sep="\t", row.names=FALSE)
    }
    result[[cpt]] <- data
    cpt <- cpt + 1
  }
  return (result)
}

getMobileSessions <- function(path=".") {
  mobileSessions <- list.files(path=path, include.dirs=TRUE, recursive=TRUE, full.names=TRUE)
  mobileSessions <- mobileSessions[file.info(mobileSessions)$isdir & has.files(mobileSessions)]
  return(mobileSessions)
}



